package com.android.qjpmc.manager;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;

import com.android.qjpmc.widget.manager.RxJavaHttpManager;
import com.android.qjpmc.widget.manager.retrofit.RetrofitJsonManager;
import com.android.qjpmc.widget.permissions.PermissionListener;
import com.android.qjpmc.widget.permissions.PermissionsUtil;
import com.android.qjpmc.widget.retrofithelper.rxsubscriber.CommonObserver;
import com.orhanobut.logger.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

import static android.content.Context.LOCATION_SERVICE;

public class LocationLocalManager {

    private static class LocationLocalManagerSingleton {
        private static final LocationLocalManager INSTANCE = new LocationLocalManager();

    }

    public static LocationLocalManager getInstance() {
        return LocationLocalManager.LocationLocalManagerSingleton.INSTANCE;
    }

    private LocationLocalManager() {
    }

    public void initLocation(Context context) {

        String[] permissions = {
                Manifest.permission.ACCESS_FINE_LOCATION,

        };
        PermissionsUtil.requestPermission(context, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        initLocationManager(context);
                        startLoopUpload(context);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        //  ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, permissions, false, null
        );


    }

    private void initLocationManager(Context context) {
        //获取地理位置管理器
        LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        uploadLocationInfo(bestLocation);
        Logger.d("initLocationManager" + bestLocation.getLatitude() + "----" + bestLocation.getLongitude());
    }

    private void startLoopUpload(Context context) {
        Observable.interval(4, TimeUnit.HOURS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                initLocationManager(context);
            }
        });

    }

    private void uploadLocationInfo(Location bestLocation) {
        Map<String, Object> map = new HashMap<>();
        map.put("latitude", bestLocation.getLatitude());
        map.put("longitude", bestLocation.getLongitude());
        RetrofitJsonManager.getInstance().getApiService().uploadLocation(map).compose(RxJavaHttpManager.applyTransformer()).subscribe(new CommonObserver<Object>() {
        });

    }
}
